package eliauk.fun.flowabledemo.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import eliauk.fun.flowabledemo.FlowableConstant;
import eliauk.fun.flowabledemo.config.MyDefaultProcessDiagramGenerator;
import eliauk.fun.flowabledemo.dto.ApproveDto;
import eliauk.fun.flowabledemo.service.MyTaskService;
import eliauk.fun.flowabledemo.vo.CommentVo;
import eliauk.fun.flowabledemo.vo.Person;
import eliauk.fun.flowabledemo.vo.TaskVo;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.common.engine.impl.util.IoUtil;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Comment;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.service.impl.persistence.entity.HistoricTaskInstanceEntityImpl;
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

@RestController
@RequestMapping("inside")
@Slf4j
public class InsideTurnController {

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private HistoryService historyService;

    @Resource
    private ProcessEngine processEngine;


    @Autowired
    private MyTaskService myTaskService;

    @GetMapping("start")
    public String startProcess() {
        String processId = "InsideTurn:1:54120fdb-a593-11ef-a3ec-005056c00008";
        Map<String, Object> variables = new HashMap<>();
        variables.put("assignee", "coca cola"); // 设置下个任务的处理人 是 coca cola （必须设置，因为流程图中已经占位，若无此字段流程图不完整）
        DateTime dateTime = DateUtil.offsetMinute(new Date(), 20);
        // 设置下个任务处理人的自动审核时间为 20 min 后 （必须设置，因为流程图中已经占位，若无此字段流程图不完整）
        // taskService 有查询已经超时的任务 配合 定时任务可以做超时处理 比如超时了短信提醒，超时了就自动通过
        // dateTime 为空，代表这个任务没有超时时间，taskService有查询已经超时的任务不会查找出来
        variables.put("dueDate", dateTime);
        //设置流程发起人
        Authentication.setAuthenticatedUserId("me");
        // processId 流程id  appealId 为这个流程的业务id variables 为流程变量
        runtimeService.startProcessInstanceById(processId, "appealId---0001", variables);
        //这个方法最终使用一个ThreadLocal类型的变量进行存储，也就是与当前的线程绑定，所以流程实例启动完毕之后，需要设置为null，防止多线程的时候出问题。
        Authentication.setAuthenticatedUserId(null);
        return "局内转办审核流程成功启动";
    }

    @GetMapping("getTask/{taskId}")
    public TaskVo getTask(@PathVariable String taskId) {
        return myTaskService.getTask(taskId);
    }

    @PostMapping("/approve")
    public String completeTask(@RequestBody ApproveDto approveDto) {
        // 参数校验
        Assert.notNull(approveDto.getTaskId());
        Task task = taskService.createTaskQuery().taskId(approveDto.getTaskId()).singleResult();
        Assert.notNull(task, "任务不存在或者已经审核完成");

        // 审批添加批注
        taskService.addComment(task.getId(), task.getProcessInstanceId(), "taskResult", approveDto.getResult().toString());
        taskService.addComment(task.getId(), task.getProcessInstanceId(), "taskComment", approveDto.getComment());
        if (approveDto.getResult()) {
            taskService.addComment(task.getId(), task.getProcessInstanceId(), "taskResultMessage", "通过");
        } else {
            taskService.addComment(task.getId(), task.getProcessInstanceId(), "taskResultMessage", "驳回");
        }
        // 审批完成
        HashMap<String, Object> variables = new HashMap<>();
        variables.put(FlowableConstant.CHECK_RESULT, approveDto.getResult());
        variables.put("assignee", "xiaoheizi");
        taskService.complete(task.getId(), variables);
        return "审批完成";
    }


    @RequestMapping(value = "processDiagram")
    public void createProcessDiagramPic(HttpServletResponse httpServletResponse, String processId) throws Exception {

        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (pi == null) {
            return;
        }
        Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();

        String InstanceId = task.getProcessInstanceId();
        List<Execution> executions = runtimeService
                .createExecutionQuery()
                .processInstanceId(InstanceId)
                .list();

        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution exe : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }

        /**
         * 生成流程图
         */
        BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engconf.getActivityFontName(), engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(), 1.0, true);
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            out = httpServletResponse.getOutputStream();
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }


    @GetMapping(value = "diagram/view")
    public void diagramView(String processInstanceId, HttpServletResponse httpServletResponse) {
        // 获得当前活动的节点
        String processDefinitionId;
        // 如果流程已经结束，则得到结束节点
        if (this.isFinished(processInstanceId)) {
            HistoricProcessInstance pi = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            processDefinitionId = pi.getProcessDefinitionId();
        } else {
            // 如果流程没有结束，则取当前活动节点
            // 根据流程实例ID获得当前处于活动状态的ActivityId合集
            ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            processDefinitionId = pi.getProcessDefinitionId();
        }
        List<String> highLightedActivities = new ArrayList<>();

        // 获得活动的节点
        List<HistoricActivityInstance> highLightedActivityList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceStartTime().asc().list();
        List<String> highLightedFlows = new ArrayList<>();

        for (HistoricActivityInstance tempActivity : highLightedActivityList) {
            String activityId = tempActivity.getActivityId();
            highLightedActivities.add(activityId);
            if ("sequenceFlow".equals(tempActivity.getActivityType())) {
                highLightedFlows.add(tempActivity.getActivityId());
            }
        }

        // 获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        ProcessEngineConfiguration engConf = processEngine.getProcessEngineConfiguration();

        ProcessDiagramGenerator diagramGenerator = engConf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "bmp", highLightedActivities, highLightedFlows, engConf.getActivityFontName(),
                engConf.getLabelFontName(), engConf.getAnnotationFontName(), engConf.getClassLoader(), 1.0, true);
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int length;
        try {
            out = httpServletResponse.getOutputStream();
            while ((length = in.read(buf)) != -1) {
                out.write(buf, 0, length);
            }
        } catch (IOException e) {
            log.error("操作异常", e);
        } finally {
            IoUtil.closeSilently(out);
            IoUtil.closeSilently(in);
        }
    }

    private boolean isFinished(String processInstanceId) {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        return pi == null;
    }


    /**
     * 流程申请 流转图片输入流
     */
    @GetMapping(value = "diagram/view2")
    public void getFlowDiagram(String procInsId, HttpServletResponse httpServletResponse) throws IOException {

        String procDefId;
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(procInsId)
                .singleResult();
        if (processInstance == null) {
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInsId).singleResult();
            procDefId = historicProcessInstance.getProcessDefinitionId();

        } else {
            procDefId = processInstance.getProcessDefinitionId();
        }

        BpmnModel bpmnModel = repositoryService.getBpmnModel(procDefId);
        MyDefaultProcessDiagramGenerator defaultProcessDiagramGenerator = new MyDefaultProcessDiagramGenerator();

        List<String> highLightedActivities = new ArrayList<>(); // 高亮节点集合
        List<String> highLightedFlows = new ArrayList<>(); // 高亮连线集合
        List<HistoricActivityInstance> hisActInsList = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(procInsId)
                .list(); // 查询所有历史节点信息
        hisActInsList.forEach(historicActivityInstance -> { // 遍历
            if ("sequenceFlow".equals(historicActivityInstance.getActivityType())) {
                // 添加高亮连线
                highLightedFlows.add(historicActivityInstance.getActivityId());
            } else {
                // 添加高亮节点
                highLightedActivities.add(historicActivityInstance.getActivityId());
            }
        });
        String imageType = "png"; // 生成图片的类型
        String activityFontName = "宋体"; // 节点字体
        String labelFontName = "宋体"; // 连线标签字体
        String annotationFontName = "宋体"; // 连线标签字体
        ClassLoader customClassLoader = null; // 类加载器
        double scaleFactor = 1.0d; // 比例因子，默认即可
        boolean drawSequenceFlowNameWithNoLabelDI = true; // 不设置连线标签不会画
        // 生成图片
        InputStream inputStream = defaultProcessDiagramGenerator.generateDiagram(bpmnModel, imageType, highLightedActivities
                , highLightedFlows, activityFontName, labelFontName, annotationFontName, customClassLoader,
                scaleFactor, drawSequenceFlowNameWithNoLabelDI); // 获取输入流

        // 直接写到页面，要先获取HttpServletResponse
        byte[] bytes = IoUtil.readInputStream(inputStream, "flow diagram inputStream");
        httpServletResponse.setContentType("image/png");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        httpServletResponse.reset();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }


}
